import {
  fetchDownloadGetGeneratorText,
  fetchGetGeneratorText,
  fetchUpdateGetGeneratorText,
} from "@/api/server/recommend_question";
import { useDocGenerationStore } from "@/store";
import { useUpdateEffect } from "ahooks";
import { Button, message, Spin } from "antd";
import dayjs from "dayjs";
import { PropsWithChildren, useEffect, useRef, useState } from "react";
import { SvgIcon } from "../../components/SvgIcon";
import { VditorEditor } from "@/components/VditorEditor";
import { CloudDownloadOutlined } from "@ant-design/icons";
import { Loading } from "@/components/Loading";

interface IDocGenerationInfoProps {
  infoKey?: string;
}

export function DocGenerationInfo(
  props: PropsWithChildren<IDocGenerationInfoProps>
) {
  const activeKey = useDocGenerationStore((state) => state.activeKey);
  const [fileName, setFileName] = useState("未命名文书");
  const [fileTime, setFileTime] = useState("未命名文书");
  const [markdownValue, setMarkdownValue] = useState("");
  const vdRef = useRef(null);
  const [loading, setLoading] = useState(false);

  useUpdateEffect(() => {
    initDoc(activeKey);
  }, [activeKey]);

  function initDoc(chat_id) {
    setLoading(true);

    fetchGetGeneratorText({
      chat_id: chat_id,
    })
      .then((res) => {
        const updateTime = res.data.data.created_at;
        const messagesLast = res.data?.data?.[res.data?.data?.length - 1];

        setFileTime(dayjs(updateTime).format("YYYY-MM-DD HH:mm:ss"));
        setFileName(messagesLast?.query);

        const markdown = messagesLast?.content;
        setMarkdownValue(markdown);
        setLoading(false);
      })
      .catch((err) => {
        setLoading(false);
      });
  }

  useEffect(() => {
    initDoc(activeKey);
  }, []);

  const onSaveDoc = async () => {
    const markdown = vdRef.current?.getValue();

    await fetchUpdateGetGeneratorText({
      chat_id: activeKey,
      content: markdown,
    });

    message.success("保存成功");
  };

  const onDownloadDoc = async () => {
    const markdown = vdRef.current?.getValue();

    const res = await fetchDownloadGetGeneratorText({
      chat_id: activeKey,
      title: fileName,
      markdown_data: markdown,
    });

    if (res?.data?.download_link) {
      window.open(res.data.download_link, "_blank");
    }

    message.success("下载成功");
  };

  return (
    <div className="flex flex-col flex-1 min-h-0 relative">
      <div
        className="flex flex-row justify-between bg-white"
        style={{
          padding: "6px 16px 6px 16px",
          borderBottom: "1px solid rgb(226, 226, 226)",
        }}
      >
        <div></div>
        <div className="flex flex-row gap-[16px]">
          <Button
            onClick={() => onDownloadDoc()}
            icon={<CloudDownloadOutlined />}
            style={{ color: "var(--T-Theme-3)" }}
          >
            下载文书
          </Button>

          <Button
            onClick={() => onSaveDoc()}
            icon={<SvgIcon name="icon-charubiji" />}
            style={{ color: "var(--T-Theme-3)" }}
          >
            保存文书
          </Button>
        </div>
      </div>
      <div className="flex-1 min-h-0 w-full p-[16px] flex flex-row justify-center items-start overflow-auto">
        <div className="w-[60%] min-h-full bg-white">
          <div
            className="mx-[32px]"
            style={{ borderBottom: "1px solid #e2e2e2" }}
          >
            <div className="text-[20px] text-[#333] text-center mt-[28px] mb-[12px]">
              {fileName}
            </div>
            <div className="text-right">
              <span className="text-[#666e79] font-[14px] mt-[6px]">
                {fileTime}
              </span>
            </div>
          </div>
          <VditorEditor value={markdownValue} ref={vdRef} />
        </div>
      </div>
      {loading && (
        <Loading>
          <div>正在加载中，请稍等...</div>
        </Loading>
      )}
    </div>
  );
}
